<script setup>

import {AddOutline, Trash} from "@vicons/ionicons5";
import ConfirmButton from "@/components/confirm-button/index.vue";
import {NButton, NSpace, useDialog, useMessage} from "naive-ui";
import {renderIcon} from "@/utils/index.js";
import {useSysRoleMutations} from "@/composables/sys/role.js";
import DictSelect from "@/components/dict-select/index.vue";
import {dictCode} from "@/common/constant.js";
import {usePermission} from "@/composables/use-permission.js";

const {hasPermission} = usePermission()
const message = useMessage()
const checkedRowKeys = ref([])
const sysRoleMutations = useSysRoleMutations()
const emits = defineEmits([
  'on-add', 'on-edit', 'on-delete', 'on-delete-batch', 'update:page', 'update:pageSize'
])

defineProps({
  data: {
    type: Array,
    required: true,
    default: () => []
  },
  page: {
    type: Number,
    required: true
  },
  pageSize: {
    type: Number,
    required: true
  },
  itemCount: {
    type: Number,
    required: true
  }
})

// 列配置
const columns = [
  {
    type: 'selection',
    width: 60
  },
  {
    title: '角色名称',
    key: 'name',
    align: 'center',
    width: 150
  },
  {
    title: '角色编码',
    key: 'code',
    align: 'center',
    width: 150
  },
  {
    title: '备注',
    key: 'remark',
    align: 'center',
  },
  {
    title: '创建时间',
    key: 'createdAt',
    align: 'center',
  },
  {
    title: '创建人',
    key: 'createdBy',
    align: 'center',
    render(row) {
      return h(DictSelect, {
        code: dictCode.SYS_USER,
        value: row.createdBy,
        disabled: true
      })
    }
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    align: 'center',
  },
  {
    title: '更新人',
    key: 'updatedBy',
    align: 'center',
    render(row) {
      return h(DictSelect, {
        code: dictCode.SYS_USER,
        value: row.createdBy,
        disabled: true
      })
    }
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    width: 200,
    render(row) {
      const isAdminRole = row.code === 'admin'
      return [
        hasPermission('delete') && !isAdminRole ? h(ConfirmButton,
            {
              text: '删除',
              type: 'error',
              size: 'tiny',
              quaternary: true,
              onPositiveClick: async () => {
                try {
                  await sysRoleMutations.deleteById.mutateAsync(row.id)
                  message.success('删除成功')
                } catch (e) {
                  console.error("删除失败", e)
                }
              }
            }
        ) : null,
        hasPermission('edit') && !isAdminRole ? h(NButton, {
          type: 'primary',
          size: 'tiny',
          quaternary: true,
          onClick: () => {
            emits('on-edit', row.id)
          }
        }, {
          default: () => '编辑'
        }) : null,
      ]
    }
  }
]

// 删除选中
const handleDeleteBatch = async () => {
  try {
    await sysRoleMutations.deleteBatch.mutateAsync(checkedRowKeys.value)
    message.success('删除成功')
    checkedRowKeys.value = []
  } catch (e) {
    console.error("批量删除失败", e)
  }
}
</script>

<template>
  <n-space vertical>
    <n-space reverse>
      <n-button
          type="primary"
          size="small"
          :render-icon="renderIcon(AddOutline)"
          @click="$emit('on-add')">
        <span>新增</span>
      </n-button>
      <confirm-button
          text="批量删除"
          type="error" size="small"
          :disabled="checkedRowKeys.length === 0"
          :render-icon="renderIcon(Trash)"
          @positive-click="handleDeleteBatch"
      />
    </n-space>
    <n-data-table
        ref="table"
        remote
        v-model:checked-row-keys="checkedRowKeys"
        :row-key="(row) => row.id"
        :columns="columns"
        :data="data"
        :pagination="{
        page,
        pageSize,
        itemCount: itemCount,
        showSizePicker: true,
        showQuickJumper: true,
        goto: () => '跳至',
        pageSizes: [10, 20, 50, 100],
        showTotal: true,
        prefix: () => `共${itemCount}条`,
        'onUpdate:page': (_page) => $emit('update:page', _page),
        'onUpdate:pageSize': (_pageSize) => $emit('update:pageSize', _pageSize),
      }">
    </n-data-table>
  </n-space>
</template>

<style scoped>

</style>